<template>
  <div>
    <el-form ref="form" :model="bindingAccount" :rules="rules" label-width="80px" size="mini">
      <el-form-item label="账号" prop="account" :error="formError.account">
        <el-input
          v-model="bindingAccount.account"
          placeholder="账号"
          style="width: 200px"
          :disabled="true"
          suffix-icon="el-icon-lock"
        ></el-input>
        <el-button
          :type="countDownTime === constant.QR_CODE_TIME || countDownTime === 0 ? 'primary' : ''"
          class="ml10"
          @click="loadQrCode"
          :disabled="
            !bindingAccount.account || countDownTime !== constant.QR_CODE_TIME || isQrCodeLoading || countDownTime === 0
          "
        >
          {{
            countDownTime === constant.QR_CODE_TIME || countDownTime === 0 ? '获取二维码' : `重新获取${countDownTime}s`
          }}
        </el-button>
      </el-form-item>
    </el-form>

    <div class="qr-code">
      <el-image
        :class="[currentStep === '2' ? 'disable' : '']"
        v-loading="isQrCodeLoading"
        style="width: 300px; height: 300px"
        :src="qrCodeUrl"
        fit="fill"
      >
        <div slot="error" class="image-slot text-gray-light">
          <template v-if="currentStep === '0'">点击"获取二维码"获取58安居客登录的二维码</template>
          <template v-else>
            <i class="el-icon-picture-outline"></i>
          </template>
        </div>
      </el-image>
    </div>

    <div class="tip text-black bold lhl mt10">
      <div v-if="currentStep === '0'">
        <div>点击"获取二维码"获取58安居客登录的二维码</div>
        <div class="fs-sm text-gray">备注：您账号所在的城市需要通过扫码的方式进行绑定账号</div>
      </div>
      <div v-if="currentStep === '1'">
        使用移动经纪人【扫一扫】扫描绑定
      </div>
      <div v-if="currentStep === '2'">
        二维码已过期，请重新获取
      </div>
    </div>
  </div>
</template>

<script>
import { PORT_CODE_AJK, PORT_CODE_XFL_MP } from '@/config/house/platform';

const QR_CODE_TIME = 41;

export default {
  name: 'PortManagementScan',

  components: {},

  props: {
    row: {
      type: Object,
      default() {
        return {};
      }
    }
  },

  data() {
    this.constant = {
      PORT_CODE_AJK,
      PORT_CODE_XFL_MP,
      QR_CODE_TIME: QR_CODE_TIME
    };
    this.timer = null; // 计时器
    return {
      isQrCodeLoading: false,
      currentStep: '0',
      qrCodeUrl: '',
      countDownTime: QR_CODE_TIME, // 验证码时间
      bindingAccount: {
        account: '',
        action: '',
        city: '',
        protId: '',
        sessionId: '',
        portType: '',
        unitId: ''
      },
      formError: {
        account: ''
      }, // 异步错误
      rules: {
        account: [{ required: true, message: '账号不能为空', trigger: 'blur' }]
      }
    };
  },

  computed: {},

  watch: {
    row: {
      handler: function(val) {
        if (!val) return;
        const { account, city, action, portType } = val;
        Object.assign(this.bindingAccount, {
          action: action || '',
          account: account || '',
          city: city || '',
          portType: portType || ''
        });
      },
      immediate: true
    }
  },

  beforeMount() {},

  mounted() {},

  beforeDestroy() {
    this.resetCountDown();
  },

  methods: {
    // 检查端口绑定状态
    async checkPortBindStatus() {
      try {
        const { account, action, city, protId, sessionId, portType, unitId } = this.bindingAccount;
        const res = await this.$api.saveQrCodeBind({
          account,
          action,
          city,
          id: protId,
          sessionId,
          siteCode: portType,
          unitId
        });
        const result = res.content || {};
        if (res && res.content && res.content.status === '1') {
          this.$message.success('绑定成功!');
          this.$emit('portChange');
          this.$emit('close');
        } else {
          this.solvePortError({
            errorCode: result.statusCode,
            errorMessage: result.reason || '',
            errorParams: result.accountVerifyVo || {}
          });
        }
      } catch (error) {
        console.log('error: ' + error);
      }
    },
    // 处理端口错误
    solvePortError({ errorCode, errorMessage, errorParams = {} }) {
      // 超时
      if (['account_login.port_qr_code_timeout'].indexOf(errorCode) !== -1) {
        this.$message.error('二维码已失效，请重新获取~');
        this.solveErrorTimeout();
        return;
      }
      // 账号错误
      // if (
      //   [
      //     'account_login.account_exist',
      //     'account_login.port_exist',
      //     'account_login.account_time_bind',
      //     'account_login.name_or_pass_fail'
      //   ].indexOf(errorCode) !== -1
      // ) {
      //   this.solveErrorAccount(errorMessage);
      //   return;
      // }
      // 默认处理
      // this.$message.error(errorMessage || '操作失败，请稍后再试~');
    },
    // 扫码超时错误
    solveErrorTimeout() {
      this.resetCountDown();
      this.currentStep = '2';
    },
    // 处理端口错误账号
    solveErrorAccount(errorMessage) {
      this.formError.account = '';
      this.$nextTick(() => {
        this.formError.account = errorMessage;
      });
    },
    // 加载图片验证码
    async loadQrCode() {
      try {
        this.isQrCodeLoading = true;
        const { account, city, portType, action } = this.bindingAccount;
        const res = await this.$api.getQrCodeLogin({
          account,
          action,
          siteCode: portType,
          city
        });
        if (res && res.isSuccess && res.content) {
          const { id, sessionId, unitId, qrCode } = res.content;
          Object.assign(this.bindingAccount, {
            protId: id,
            sessionId,
            unitId
          });
          this.qrCodeUrl = qrCode || '';
          this.currentStep = '1';
          this.startCountDown(this.checkPortBindStatus);
        } else {
          this.$message.error('二维码获取失败，请重新获取~');
        }
      } catch (error) {
        this.$message.error('二维码获取失败，请重新获取~');
        console.log('error: ' + error);
      } finally {
        this.isQrCodeLoading = false;
      }
    },
    // 倒计时器
    startCountDown(cb, time = QR_CODE_TIME) {
      if (this.countDownTime !== time) return;
      this.countDownTime--;
      this.timer = setInterval(() => {
        this.countDownTime--;
        cb && cb();
        if (this.countDownTime <= 0) {
          this.currentStep = '2';
          this.resetCountDown();
        }
      }, 1000);
    },

    // 重置倒计时
    resetCountDown() {
      this.countDownTime = QR_CODE_TIME;
      clearInterval(this.timer);
      this.timer = null;
    }
  }
};
</script>
<style lang="scss" scoped>
@import '~@/styles/colors.scss';

.qr-code {
  display: flex;
  justify-content: center;
  height: 300px;
  & /deep/ .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background-color: $lighter-gray;
  }
}
.tip {
  display: flex;
  justify-content: center;
}
.disable {
  opacity: 0.2;
}
</style>
